<?php
namespace app\index\controller;
use app\index\model\Image;
use think\Db;

//商品类
class Goods extends Base
{
    /**
     * 发布商品
     */
    public function publish()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Goods');
        if(!$validate->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        $row = db('user',[],false)->where('us_id',$data['gd_uid'])->find();

        if (!$row['us_school']) {
            $info['code']     = '400';
            $info['message']  = '请先前往个人中心完善学校等信息';
            echo displayJson($info);die;
        }

        if (empty($data['gd_image_1']) && empty($data['gd_image_2']) && empty($data['gd_image_3']) && empty($data['gd_image_4'])) {
            $info['code']     = '400';
            $info['message']  = '请至少上传一张图片';
            echo displayJson($info);die;
        }

        //图片处理
        $imgArr = array(
            'gd_image_1' => $data['gd_image_1'],
            'gd_image_2' => $data['gd_image_2'],
            'gd_image_3' => $data['gd_image_3'],
            'gd_image_4' => $data['gd_image_4']
        );

        foreach ($imgArr as $key => $val) {
            if(!empty($val)) {
                $stream  = $val;
                $tmpName = uploadBase64($stream); //将流文件保存为临时文件
                $suffix  = getSuffix($tmpName);  //获取后缀名

                if ($suffix !== false) {
                    $realName = $key.'_'.time().'_'.make_Verification_Code(6).'.'.$suffix;
                    $ret      = rename($tmpName,$realName);

                    if ($ret) {
                        //创建以邮箱为名的文件夹
                        $dir = iconv("UTF-8", "GBK", "./image/goods/".$row['us_email']);
                        if (!file_exists($dir)){
                            $make = mkdir ($dir,0777);
                            if ($make == false) {
                                $info['code']    = '400';
                                $info['message'] = '服务器分配空间失败';
                                echo displayJson($info);die;
                            }
                        }

                        //压缩图片
                        $source =  $realName;//原图片名称
                        $dst_img = './image/goods/'.$row['us_email'].'/'.$realName;//压缩后图片的名称
                        //@(Image($source))->compressImg($dst_img);
                        //@(Image($source)::compressImg($dst_img));
                        @(new Image($source))->compressImg($dst_img);

                        //删除原来的图片
                        @unlink($realName);

                        //记录图片存储路径
                        $new_dst_img = substr($dst_img, 1);

                        $data[$key] =  'http://www.taoerhuo.top/bishe/public'.$new_dst_img;
                    } else {
                        $info['code']    = '400';
                        $info['message'] = '图片获取失败';
                        echo displayJson($info);die;
                    }
                }
            }
        }

        $data['gd_school']      = $row['us_school']; //学校
        $data['gd_money']       = floatval($data['gd_money']); //获取价格的浮点值
        $data['gd_title']       = htmlspecialchars($data['gd_title']);
        $data['gd_place']       = htmlspecialchars($data['gd_place']);
        $data['gd_desc']        = htmlspecialchars($data['gd_desc']);
        //$data['gd_overdue_time'] = time() + __PASS_TIME__; //过期时间 30天
        $data['gd_create_time']  = time();

        //插入数据库
        $res = db('goods',[],false)->insert($data);

        if ($res) {
            //用户发布商品数量加一
             db('user',[],false)->where('us_id',$data['gd_uid'])->setInc('us_goods_num');

            //分类下的商品数量加一
             db('classify',[],false)->where('cf_id',$data['gd_classify'])->setInc('cf_goods_num');

            $info['code']    = '200';
            $info['message'] = '发布成功';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '服务器繁忙，请稍后重试';
            echo displayJson($info);die;
        }

    }

    /**
     * 获取当前登录用户商品列表
     */
    public function getGoodsList()
    {
        $id = input('us_id');

        $res = db('goods',[],false)->where('gd_uid',$id)->where('gd_status',1)->order('gd_create_time desc')->select();

        //获取所有分类
        $cat_list = $this->getAllClassify();

        if (!empty($res)) {
            foreach ($res as &$val) {
                $val['gd_classify_name'] = $cat_list[$val['gd_classify']];
                
            }
        }


        $info['code']    = '200';
        $info['message'] = '获取成功';
        $info['data']    = $res;
        echo displayJson($info);die;
    }

    /**
     * 修改商品状态为 已卖出
     */
    public function changeGoodsStatus()
    {
        $uid = input('uid');
        $gid = input('gid');

        if (empty($uid) || empty($gid)) {
            $info['code']     = '400';
            $info['message']  = '缺少必要参数';
            echo displayJson($info);die;
        }

        $goods_row = db('goods',[],false)->where('gd_id',$gid)->find();

        if (!$goods_row) {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架';
            echo displayJson($info);die;
        }

        //更新某个字段
        $res = db('goods',[],false)->where('gd_id',$gid)->setField('gd_goods_status','2');

        //已卖出数量加一
        db('user',[],false)->where('us_id',$uid)->setInc('us_sell_out');

        //卖出金额累加
        db('user',[],false)->where('us_id',$uid)->setInc('us_sell_money',$goods_row['gd_money']);

        if ($res) {
            $info['code']     = '200';
            $info['message']  = '操作成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '操作失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 获取分类
     */
    public function getClassify()
    {
        $res = db('classify',[],false)->where('cf_status','1')->column('cf_name','cf_id');

        if ($res) {
            $info['code']  = '200';
            $info['data']  = $res;
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '数据异常';
            echo displayJson($info);die;
        }

    }

    /**
     * 商品下 留言
     */
    public function leavingMessage()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Liu');
        if(!$validate->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        $data['ly_create_time'] = time();
        $data['ly_content']     = htmlspecialchars($data['ly_content']);

        //向卖家发送邮件
        $rowGoods  = db('goods',[],false)->where('gd_id',$data['ly_gid'])->find();
        if ($rowGoods && $rowGoods['gd_status'] == 1) {
            //卖家信息
            $mai_user = db('user', [], false)->where('us_id', $rowGoods['gd_uid'])->find();

            //留言用户信息
            $user_info = db('user', [], false)->where('us_id', $data['ly_uid'])->find();

            if ((int)$rowGoods['gd_uid'] !== (int)$data['ly_uid']) {
                //自己跟自己商品留言不发邮箱
                $send_data = array(
                    'to_email' => $mai_user['us_email'],
                    'content' => '【淘二货】您发布的商品：<span style="font-size: 20px;font-weight: bold;"> ' . $rowGoods['gd_title'] . ' </span>有新的留言,请及时查看'
                );

                sendEmail($send_data);
            }

            $data['ly_uname']  = empty($user_info['us_username']) ? $user_info['us_email'] : $user_info['us_username'];
            $data['ly_uimage'] =  $user_info['us_image'];
            //插入数据库
            $res = db('liuyan',[],false)->insert($data);

            if ($res) {
                $info['code']    = '200';
                $info['message'] = '留言成功';
                echo displayJson($info);die;
            } else {
                $info['code']    = '400';
                $info['message'] = '留言失败';
                echo displayJson($info);die;
            }
        } else {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架，操作无法完成';
            echo displayJson($info);die;
        }
    }

    /**
     * 删除自己的留言
     */
    public function delMyLiuyan()
    {
        $lid = input('lid'); //留言id
        $uid = input('uid'); //用户id

        if (empty($lid) || !isset($lid)) {
            $info['code']     = '401';
            $info['message']  = '非法操作，系统自动退出';
            echo displayJson($info);die;
        }

        $row = db('liuyan',[],false)->where('ly_id',$lid)->find();

        if ((int)$row['ly_uid'] !== (int)$uid) {
            $info['code']     = '400';
            $info['message']  = '禁止删除他人留言';
            echo displayJson($info);die;
        }

        if ($row['ly_status'] == 1) {
            //更新某个字段 返回更新的条数
            $res = db('liuyan',[],false)->where('ly_id',$lid)->setField('ly_status','2');

            if ($res > 0) {
                $info['code']     = '200';
                $info['message']  = '删除成功';
                echo displayJson($info);die;
            } else {
                $info['code']     = '400';
                $info['message']  = '删除失败';
                echo displayJson($info);die;
            }
        } else {
            $info['code']     = '400';
            $info['message']  = '该留言已被删除，请刷新后重试';
            echo displayJson($info);die;
        }
    }

    
    /**
     * 收藏商品
     */
    public function collectGoods()
    {
        $data = input('post.');

        //存储用户id、商品id、收藏时间
        if (empty($data['cc_uid']) || empty($data['cc_gid'])) {
            $info['code']     = '401';
            $info['message']  = '参数丢失，请重新登录';
            echo displayJson($info);die;
        }

        $getGoodsStatus = db('goods',[],false)->where('gd_id',$data['cc_gid'])->where('gd_status',1)->find();

        if (!$getGoodsStatus) {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架';
            echo displayJson($info);die;
        }

        $data['cc_create_time'] = time();

        $res = db('collect',[],false)->insert($data);

        if ($res) {
            //商品收藏量加一
            db('goods',[],false)->where('gd_id',$data['cc_gid'])->where('gd_status',1)->setInc('gd_collection_num');

            $info['code']     = '200';
            $info['message']  = '收藏成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '收藏失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 取消收藏商品
     */
    public function delCollect()
    {
        $gid = input('cc_gid');//商品id
        $uid = input('cc_uid');//用户id

        if (empty($gid) || empty($uid)) {
            $info['code']     = '401';
            $info['message']  = '参数丢失，请重新登录';
            echo displayJson($info);die;
        }

        //删除收藏数据
        $res = db('collect',[],false)->where('cc_uid',$uid)->where('cc_gid',$gid)->delete();

        if ($res) {
            //商品收藏量减一
            db('goods',[],false)->where('gd_id',$gid)->where('gd_collection_num','>',0)->where('gd_status',1)->setDec('gd_collection_num');

            $info['code']     = '200';
            $info['message']  = '取消成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '取消失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 获取收藏商品列表
     */
    public function getCollectList()
    {
        $uid  = input('cc_uid');

        if (!$uid) {
            $info['code']     = '401';
            $info['message']  = '参数丢失，请重新登录';
            echo displayJson($info);die;
        }

        $time = time();

        $list = Db::query("select gd.*,cc.cc_create_time from cs_collect cc left join cs_goods gd on cc.cc_gid = gd.gd_id where cc.cc_uid = $uid and gd.gd_status = 1 and gd.gd_goods_status = 1 order by cc.cc_create_time desc");

        foreach ($list as $key => $val) {
            $list[$key]['gd_create_time'] = date('Y-m-d',$val['gd_create_time']);
            $list[$key]['cc_create_time'] = date('Y-m-d',$val['cc_create_time']);

            unset($list[$key]['gd_classify']);
            unset($list[$key]['gd_image_2']);
            unset($list[$key]['gd_image_3']);
            unset($list[$key]['gd_image_4']);
            unset($list[$key]['gd_uid']);
            unset($list[$key]['gd_goods_status']);
            unset($list[$key]['gd_status']);
            unset($list[$key]['gd_del_aid']);
            unset($list[$key]['gd_del_note']);
            unset($list[$key]['gd_del_time']);
            unset($list[$key]['gd_report_note']);
            unset($list[$key]['gd_report_num']);
        }

        $info['code']     = '200';
        $info['message']  = '获取成功';
        $info['data']     = $list;
        echo displayJson($info);die;
    }

    /**
     * 重新上架
     */
    public function againPublish()
    {
        $gid = input('gid');//商品id
        $uid = input('uid');//用户id

        if (!$gid || !$uid) {
            $info['code']     = '401';
            $info['message']  = '异常请求,请重新登录';
            echo displayJson($info);die;
        }

        $row = db('goods',[],false)
            ->where('gd_id',$gid)
            ->where('gd_uid',$uid)
            ->where('gd_goods_status',1)
            ->where('gd_status',1)
            ->find();

        if (!$row) {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架';
            echo displayJson($info);die;
        }

        if ($row['gd_overdue_time'] > time()) {
            $info['code']     = '400';
            $info['message']  = '该商品未过期，不可重新上架';
            echo displayJson($info);die;
        }

        $set['gd_create_time']  = time();

        $set['gd_overdue_time'] = time() + __PASS_TIME__;
        $res = db('goods',[],false)->where('gd_id',$gid)->where('gd_uid',$uid)->update($set);

        if ($res) {
            $info['code']     = '200';
            $info['message']  = '重新上架成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '重新上架失败';
            echo displayJson($info);die;
        }
    }
    
    /**
     * 修改商品信息
     */
    public function editGoodsInfo()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Goods');
        if(!$validate->scene('edit')->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        $row = db('goods',[],false)->where('gd_id',$data['gd_id'])->find();

        if (!$row) {
            $info['code']     = '400';
            $info['message']  = '商品不存在';
            echo displayJson($info);die;
        }
        
        $set['gd_title'] = $data['gd_title'];
        $set['gd_money'] = $data['gd_money'];
        $set['gd_desc']  = $data['gd_desc'];

        $res = db('goods',[],false)->where('gd_id',$data['gd_id'])->update($set);

        if ($res) {
            $info['code']     = '200';
            $info['message']  = '修改成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '修改失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 删除商品信息
     */
    public function delGoods()
    {
        $gid = input('gd_id');

        if (empty($gid)) {
            $info['code']     = '401';
            $info['message']  = '数据异常，请重新登录';
            echo displayJson($info);die;
        }

        $row = db('goods',[],false)->where('gd_id',$gid)->where('gd_status',1)->find();

        if (!$row) {
            $info['code']     = '400';
            $info['message']  = '商品不存在，请重新确认';
            echo displayJson($info);die;
        }

        $set['gd_status']   = 2;
        $set['gd_del_aid']  = $row['gd_uid'];
        $set['gd_del_note'] = '用户操作删除';
        $set['gd_del_time'] = time();

        $res = db('goods',[],false)->where('gd_id',$gid)->update($set);

        if ($res) {
            //用户发布商品数量减一
            db('user',[],false)->where('us_id',$row['gd_uid'])->setDec('us_goods_num');

            //分类下的商品数量减一
            db('classify',[],false)->where('cf_id',$row['gd_classify'])->setDec('cf_goods_num');

            $user =  db('user',[],false)->where('us_id',$row['gd_uid'])->find();

            //删除原来的图片
            $img_url = './image/goods/'.$user['us_email'].'/';

            @unlink($img_url.explode('/',$row['gd_image_1'])[8]);
            @unlink($img_url.explode('/',$row['gd_image_2'])[8]);
            @unlink($img_url.explode('/',$row['gd_image_3'])[8]);
            @unlink($img_url.explode('/',$row['gd_image_4'])[8]);

            $info['code']     = '200';
            $info['message']  = '删除成功';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '服务器繁忙，请刷新后重试';
            echo displayJson($info);die;
        }
    }



}